/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import {
  ConfigService,
  ControlVO,
  CTX,
  GridController,
  MDCtrlLoadParams,
} from '@ibiz-template/runtime';
import { IDEGrid } from '@ibiz/model-core';
import { IPivotTableState } from './pivottable.state';

export class PivotTableController extends GridController {
  /**
   * @description 透视表配置服务
   * @type {(ConfigService | undefined)}
   * @memberof PivotTableController
   */
  configService: ConfigService | undefined;

  /**
   * @description  透视表状态
   * @type {IPivotTableState}
   * @memberof PivotTableController
   */
  declare state: IPivotTableState;

  /**
   * @description 分组模式
   * @type {('default' | 'tree')}
   * @memberof PivotTableController
   */
  public groupMode: 'default' | 'tree' = 'default';

  constructor(model: IDEGrid, context: IContext, params: IParams, ctx: CTX) {
    super(model, context, params, ctx);
    this.initConfig();
  }

  protected initState(): void {
    super.initState();
    this.state.config = {};
    this.state.fields = [];
  }

  protected async onCreated(): Promise<void> {
    await super.onCreated();
    this.initFields();
    if (this.controlParams.groupmode) {
      this.groupMode = this.controlParams.groupmode;
    }
  }

  async afterLoad(
    args: MDCtrlLoadParams,
    items: ControlVO[],
  ): Promise<ControlVO[]> {
    await super.afterLoad(args, items);
    await this.loadConfig();
    this.state.items = items.map(item => {
      const result: IData = {};
      Object.keys(item).forEach(field => {
        result[field] = this.getCodeListValue(item[field], field);
      });
      return result;
    });
    return items;
  }

  /**
   * @description 获取代码表值
   * @param {string} value
   * @param {string} field
   * @returns {*}
   * @memberof PivotTableController
   */
  getCodeListValue(value: string, field: string): string {
    const column = this.fieldColumns[field];
    if (column && column.codeListItems) {
      const item = column.codeListItems.find(x => x.value === value);
      return item?.text || value;
    }
    return value;
  }

  /**
   * @description 初始化属性字段
   * @protected
   * @memberof PivotTableController
   */
  protected initFields(): void {
    const { degridColumns = [] } = this.model;
    this.state.fields = degridColumns.map(item => {
      return {
        codeName: item.codeName,
        caption: item.caption,
      };
    });
  }

  protected initConfig(): void {
    // 初始化服务
    this.configService = new ConfigService(
      this.model.appId!,
      'pivottable',
      `pivottable_${(
        this.view as IData
      ).name.toLowerCase()}_${this.model.codeName?.toLowerCase()}`,
    );
  }

  /**
   * @description 加载配置
   * @returns {*}  {Promise<IData>}
   * @memberof PivotTableController
   */
  async loadConfig(): Promise<void> {
    if (!this.configService) {
      return;
    }
    const res = await this.configService!.load();
    if (res && res.model) {
      this.state.config = JSON.parse(res.model);
    }
  }

  /**
   * @description 保存配置
   * @param {IData} model
   * @returns {*}  {Promise<void>}
   * @memberof PivotTableController
   */
  async saveConfig(model: IData): Promise<void> {
    const data: IData = {
      model: JSON.stringify(model),
    };
    await this.configService!.save(data);
  }

  /**
   * @description 计算分组数据
   * @param {*} groupParams
   * @returns {*}  {Promise<void>}
   * @memberof PivotTableController
   */
  async execGroup(groupParams: any): Promise<void> {
    const rowKeys = groupParams.map((x: IData) => x.groupFieldId);
    this.state.config.rows = rowKeys;
  }
}
